package kinectKata.service;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import kinectData.models.DataReceiver;
import kinectData.models.ProjectSettings;

/**
 * Client connection to receive Kinect data.
 * 
 * @author Markus L�chtefeld (loechti)
 */
public class KinectDataThread extends Thread {

	private DatagramSocket sensorSocketServer;
	private DataReceiver srv;
	
	public KinectDataThread(DataReceiver server) {
		this.srv = server;
	}

	public void run() {
		while (true) {
			try {
				sensorSocketServer = new DatagramSocket(ProjectSettings.KINECT_PORT);			
				while (true) {
					if (sensorSocketServer != null) {
						byte[] buf = new byte[2048];
						DatagramPacket packet = new DatagramPacket(buf, buf.length);
						try {
							sensorSocketServer.receive(packet);
							String data = new String(packet.getData()).trim();
							if (!data.toLowerCase().contains("skeleton")) {
								srv.addSkeleton(data);	
							}
						} catch (IOException e) {
							System.err.println("Failed to receive packet " + e.getMessage());
							e.printStackTrace();
						}
					}
				}
			} catch (BindException e) {
				e.printStackTrace();
				System.err.println("Failed to bind to socket on port " + 
				  ProjectSettings.KINECT_PORT + " " + e.getMessage());
			}  catch (SocketException e) {
				e.printStackTrace();
				System.err.println("Failed to connect to socket on port " + 
				  ProjectSettings.KINECT_PORT + " " + e.getMessage());
			} catch (Exception e) {
				e.printStackTrace();
				System.err.println("Failed to connect to socket on port " + 
				  ProjectSettings.KINECT_PORT + " " + e.getMessage());
				sensorSocketServer.close();
				sensorSocketServer = null;
			}
		}
	}
}
